﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.WebControls;

namespace Card.Utility
{
    /// <summary>
    /// 验证Helper。
    /// </summary>
    public class ValidationHelper
    { 
        public ValidationHelper()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// 字符串是否是有效的数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNumeric(string str)
        {
            System.Text.RegularExpressions.Regex reg1
                = new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*$");
            return reg1.IsMatch(str.Trim());
        }
        /// <summary>
        /// 字符串是否是有效的日期
        /// </summary>
        /// <param name="strDate"></param>
        /// <returns></returns>
        public static bool IsDateTime(string strDate)
        {
            DateTime dtDate;
            bool bValid = true;
            try
            {
                dtDate = DateTime.Parse(strDate.Trim());
            }
            catch (FormatException)
            {
                // 如果解析方法失败则表示不是日期性数据
                bValid = false;
            }
            return bValid;
        }

        //验证是否为电话号码
        public static bool IsTelephoneNumber(string strIn)
        {
            return Regex.IsMatch(strIn, @"(d+-)?(d{4}-?d{7}|d{3}-?d{8}|^d{7,8})(-d+)?");
        }

        //验证IP
        public static bool IsIPAddress(string strIn)
        {
            return Regex.IsMatch(strIn, @"^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$");
        }
        private static Regex RegNumber = new Regex("^(-)?(0|[1-9][0-9]*)$");
        private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
        private static Regex RegDecimal = new Regex("^[-]?(0|[1-9][0-9]{0,2}(\\,?[0-9]{3})*)(\\.\\d+)?$");
        private static Regex RegDecimalSign = new Regex("^[-]?(0|[1-9][0-9]{0,2}(\\,?[0-9]{3})*)(\\.\\d+)?$"); //等价于^[+-]?\d+[.]?\d+$ 
        private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-.]+\\.(com|cn|net|org|edu|mil|tv|biz|info)$");//w 英文字母或数字的字符串，和 [a-zA-Z0-9] 语法一样 
        private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");

        #region 数字字符串检查
        /// <summary> 
        /// 检查Request查询字符串的键值，是否是数字，最大长度限制 
        /// </summary> 
        /// <param name="req">Request</param> 
        /// <param name="inputKey">Request的键值</param> 
        /// <param name="maxLen">最大长度</param> 
        /// <returns>返回Request查询字符串</returns> 
        public static string FetchInputDigit(HttpRequest req, string inputKey, int maxLen)
        {
            string retVal = string.Empty;
            if (inputKey != null && inputKey != string.Empty)
            {
                retVal = req.QueryString[inputKey];
                if (null == retVal)
                    retVal = req.Form[inputKey];
                if (null != retVal)
                {
                    retVal = SqlText(retVal, maxLen);
                    if (!IsNumber(retVal))
                        retVal = string.Empty;
                }
            }
            if (retVal == null)
            {
                retVal = string.Empty;
            }
            return retVal;
        }

        /// <summary> 
        /// 是否数字字符串 
        /// </summary> 
        /// <param name="inputData">输入字符串</param> 
        /// <returns></returns> 
        public static bool IsNumber(string inputData)
        {
            Match m = RegNumber.Match(inputData.Trim());
            return m.Success;
        }

        /// <summary> 
        /// 是否数字字符串可带正负号 
        /// </summary> 
        /// <param name="inputData">输入字符串</param> 
        /// <returns></returns> 
        public static bool IsNumberSign(string inputData)
        {
            Match m = RegNumberSign.Match(inputData.Trim());
            return m.Success;
        }

        /// <summary> 
        /// 是否是浮点数 
        /// </summary> 
        /// <param name="inputData">输入字符串</param> 
        /// <returns></returns> 
        public static bool IsDecimal(string inputData)
        {
            Match m = RegDecimal.Match(inputData.Trim());
            return m.Success;
        }

        /// <summary> 
        /// 是否是浮点数可带正负号 
        /// </summary> 
        /// <param name="inputData">输入字符串</param> 
        /// <returns></returns> 
        public static bool IsDecimalSign(string inputData)
        {
            Match m = RegDecimalSign.Match(inputData.Trim());
            return m.Success;
        }
        #endregion

        #region 中文检测
        /// <summary> 
        /// 检测是否有中文字符 
        /// </summary> 
        /// <param name="inputData"></param> 
        /// <returns></returns> 
        public static bool IsHasCHZN(string inputData)
        {
            Match m = RegCHZN.Match(inputData);
            return m.Success;
        }
        #endregion
        #region 邮件地址
        /// <summary> 
        /// 邮箱验证 
        /// </summary> 
        /// <param name="inputData">输入字符串</param> 
        /// <returns></returns> 
        public static bool IsEmail(string inputData)
        {
            Match m = RegEmail.Match(inputData);
            return m.Success;
        }
        #endregion
        #region 身份证验证
        /// <summary>
        /// 验证方法
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static bool CheckIDCard(string Id)
        {
            if (Id.Length == 18)
            {
                bool check = CheckIDCard18(Id);
                return check;
            }
            else if (Id.Length == 15)
            {
                bool check = CheckIDCard15(Id);
                return check;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 18位身份证号码
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static bool CheckIDCard18(string Id)
        {
            long n = 0;
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证 
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证 
            }
            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证 
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = Id.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证 
            }
            return true;//符合GB11643-1999标准 
        }
        /// <summary>
        /// 15位身份证号码
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static bool CheckIDCard15(string Id)
        {
            long n = 0;
            if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证 
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证 
            }
            string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证 
            }
            return true;//符合15位身份证标准 
        }
        #endregion
        #region 其他
        /// <summary> 
        /// 检查字符串最大长度，返回指定长度的串 
        /// </summary> 
        /// <param name="sqlInput">输入字符串</param> 
        /// <param name="maxLength">最大长度</param> 
        /// <returns></returns>          
        public static string SqlText(string sqlInput, int maxLength)
        {
            if (sqlInput != null && sqlInput != string.Empty)
            {
                sqlInput = sqlInput.Trim();
                if (sqlInput.Length > maxLength)//按最大长度截取字符串 
                    sqlInput = sqlInput.Substring(0, maxLength);
            }
            return sqlInput;
        }

        /// <summary> 
        /// 字符串编码 
        /// </summary> 
        /// <param name="inputData"></param> 
        /// <returns></returns> 
        public static string HtmlEncode(string inputData)
        {
            return HttpUtility.HtmlEncode(inputData);
        }
        /// <summary> 
        /// 设置Label显示Encode的字符串 
        /// </summary> 
        /// <param name="lbl"></param> 
        /// <param name="txtInput"></param> 
        public static void SetLabel(Label lbl, string txtInput)
        {
            lbl.Text = HtmlEncode(txtInput);
        }
        public static void SetLabel(Label lbl, object inputObj)
        {
            SetLabel(lbl, inputObj.ToString());
        }
        #endregion
    }
}
